package com.example.smartall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smartall.R;
import com.example.smartall.adapter.OrderAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.entity.OrderBannerBean;
import com.example.smartall.entity.OrderBean;
import com.example.smartall.entity.OrderThemeTypeBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OrderActivity extends BaseActivity {
    private int pageNum = 1;
    private int nearListCount;

    private ImageView imBack;
    private TextView tvTitle;
    private EditText etSearch;
    private Button btSearch, btLoadMore;
    private Banner banner;
    private TabLayout tabLayout;
    private ListView list, nearList;

    private List<OrderBannerBean.RowsBean> bannerBeanList;
    private List<OrderThemeTypeBean.DataBean> themeTypeBeanList;
    private List<OrderBean.RowsBean> orderBeanList;
    private List<OrderBean.RowsBean> nearOrderBeanList;

    private OrderAdapter orderAdapter;
    private OrderAdapter nearOrderAdapter;

    private MHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        handler = new MHandler();

        init();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBannerData();
        getOrderThemeType();
        getNearOrderList(pageNum);
    }

    @Override
    public void init() {
        bannerBeanList = new ArrayList<>();

        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        etSearch = (EditText) findViewById(R.id.et_search);
        btSearch = (Button) findViewById(R.id.bt_search);
        btLoadMore = (Button) findViewById(R.id.bt_loadMore);
        banner = (Banner) findViewById(R.id.banner);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        list = (ListView) findViewById(R.id.list);
        nearList = (ListView) findViewById(R.id.nearList);

        tvTitle.setText("(￣▽￣)～■干杯□～(￣▽￣)");

        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    public void initEvent() {
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OrderActivity.this.finish();
            }
        });
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                //TODO 轮播点击事件
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                getTypeOfOrderList((Integer) tab.getTag());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        btLoadMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (nearOrderBeanList.size() < 1) {
                    showToast("稍等正在努力加载中");
                } else {
                    if (pageNum*8 > nearListCount){
                        showToast("没有更多店家数据了！");
                    }else {
                        getNearOrderList(++pageNum);
                    }
                }
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH){
                    migrateToSearchResultActivity();
                }
                return false;
            }
        });
        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                migrateToSearchResultActivity();
            }
        });
    }

    private void migrateToSearchResultActivity(){
        Intent intent = new Intent(OrderActivity.this,OrderSearchResultActivity.class);
        intent.putExtra("key",etSearch.getText().toString().trim());
        startActivity(intent);
    }

    private void getBannerData() {
        Api.config(ApiConfig.ORDER_BANNER, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                OrderBannerBean bean = new Gson().fromJson(res, OrderBannerBean.class);
                if (bean.getCode() == 200) {
                    bannerBeanList = bean.getRows();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    private void getTypeOfOrderList(int type) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("themeId", type);
        Api.config(ApiConfig.ORDER_LIST, params).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                OrderBean bean = new Gson().fromJson(res, OrderBean.class);
                if (bean.getCode() == 200) {
                    orderBeanList = bean.getRows();
                    handler.sendEmptyMessage(0x03);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    private void getOrderThemeType() {
        Api.config(ApiConfig.ORDER_THEME_TYPE, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                OrderThemeTypeBean bean = new Gson().fromJson(res, OrderThemeTypeBean.class);
                if (bean.getCode() == 200) {
                    themeTypeBeanList = bean.getData();
                    handler.sendEmptyMessage(0x02);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    private void getNearOrderList(int pageNum) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", 8);
        Api.config(ApiConfig.ORDER_NEAR_LIST, params).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                OrderBean bean = new Gson().fromJson(res, OrderBean.class);
                if (bean.getCode() == 200) {
                    nearListCount = bean.getTotal();
                    if (nearOrderBeanList == null) nearOrderBeanList = new ArrayList<>();
                    nearOrderBeanList.addAll(bean.getRows());
                    handler.sendEmptyMessage(0x04);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
                Log.e("TAG", e.toString());
            }
        });
    }

    private void showNearOrderList() {
        if (nearOrderBeanList == null || nearOrderBeanList.size() < 1) return;
        if (nearOrderAdapter == null){
            nearOrderAdapter = new OrderAdapter(OrderActivity.this, nearOrderBeanList);
            nearList.setAdapter(nearOrderAdapter);
        }else {
            nearOrderAdapter.notifyDataSetChanged();
        }
    }

    private void showOrderList() {
        if (orderBeanList.size() < 1) return;
        orderAdapter = new OrderAdapter(OrderActivity.this, orderBeanList);
        list.setAdapter(orderAdapter);
    }

    private void setBannerUrl() {
        List<String> bannerUrls = new ArrayList<>();
        for (OrderBannerBean.RowsBean bean : bannerBeanList) {
            bannerUrls.add(ApiConfig.BASE_URL + bean.getAdvImg());
        }
        banner.setImages(bannerUrls);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(OrderActivity.this).load(o).into(imageView);
            }
        });
        banner.setDelayTime(2000);
        banner.isAutoPlay(true);
        banner.start();
        banner.startAutoPlay();
    }

    private void fillTabType() {
        for (OrderThemeTypeBean.DataBean bean : themeTypeBeanList) {
            TabLayout.Tab tab = tabLayout.newTab();
            tab.setText(bean.getThemeName());
            tab.setTag((bean.getId()));
            tabLayout.addTab(tab);
        }
    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    setBannerUrl();
                    break;
                case 0x02:
                    fillTabType();
                    break;
                case 0x03:
                    showOrderList();
                    break;
                case 0x04:
                    showNearOrderList();
                    break;
            }
        }
    }
}